package com.xuebusi.toutiao.admin.api.common.resolver;

import com.xuebusi.toutiao.admin.api.common.annotation.LoginUser;
import com.xuebusi.toutiao.admin.api.common.interceptor.AuthInterceptor;
import com.xuebusi.toutiao.admin.api.user.entity.UserEntity;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 自定义方法参数解析器
 * 为使用@LoginUser注解修饰的方法参数，注入当前登录用户
 */
@Component
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(UserEntity.class)
                && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
        //获取用户ID
        Object object = request.getAttribute(AuthInterceptor.USER_KEY, RequestAttributes.SCOPE_REQUEST);
        if (object == null || !(object instanceof UserEntity)) {
            return null;
        }
        //获取用户信息
        UserEntity userEntity = (UserEntity) object;
        return userEntity;
    }
}
